﻿Imports System.Threading
Public Class CudaController
    Friend Event SendMessage(message As String)
    Friend Event CudaRunningNow()
    Friend Event CudaStoppedNow()
    Private cudaProcess As New Process
    Friend cudaRunning As Boolean = False
    Friend watchProcessRunning As Boolean = False


    Public Sub WatchProcesses()
        Dim watchProcesses As List(Of String) = GetListOfWatchProcesses()
        Dim watchProcess As String = ""
        While True
            watchProcessRunning = False
            For Each watchProcess In watchProcesses
                If IsProcessRunning(watchProcess) Then
                    watchProcessRunning = True
                End If
            Next

            If cudaRunning And watchProcessRunning Then
                RaiseEvent SendMessage(watchProcess & " detected.")
                KillCudaProcess()
            End If
            If Not cudaRunning And Not watchProcessRunning Then
                StartCuda()
            End If
            Thread.Sleep(5000)
        End While
    End Sub

    Friend Sub KillCudaProcess()
        RaiseEvent SendMessage("Killing cudaminer.")
        RaiseEvent CudaStoppedNow()
        cudaProcess.CloseMainWindow()
        cudaProcess.Kill()
        cudaRunning = False
    End Sub

    Private Function IsProcessRunning(processName As String) As Boolean
        Dim processes As Process()
        processes = Process.GetProcessesByName(processName)
        If processes.Count > 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub StartCuda()
        RaiseEvent SendMessage("Starting cudaminer...")
        With cudaProcess.StartInfo
            .FileName = My.Settings.CudaMinerPath
            .Arguments = My.Settings.CudaMinerArgs
            .WindowStyle = My.Settings.CudaMinerVisibility
        End With
        cudaProcess.Start()
        If cudaProcess.Responding Then
            cudaRunning = True
            RaiseEvent SendMessage("CUDAminer started.")
            RaiseEvent CudaRunningNow()
        End If

    End Sub

    Private Function GetListOfWatchProcesses() As List(Of String)
        Dim watchProcesses As New List(Of String)
        For Each processName As String In My.Settings.WatchProcesses.Split(",")
            watchProcesses.Add(processName.Trim)
        Next
        Return watchProcesses
    End Function
End Class
